<template>
  <div class="card">
    <el-form label-width="auto" label-position="left" ref="formRef" :model="state.form" :rules="formRules">
      <el-row type="flex" :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="state.form.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="state.form.password" placeholder="请输入密码" show-password />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="state.form.idCard" placeholder="请输入身份证号" @input="idCardChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="state.form.gender" placeholder="请选择性别">
              <el-option v-for="item in genderDict" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日" prop="birthday">
            <el-date-picker
              v-model="state.form.birthday"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择生日"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number
              v-model="state.form.age"
              :min="1"
              :max="300"
              placeholder="请输入年龄"
              style="width: 150px"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生肖" prop="zodiac">
            <el-select v-model="state.form.zodiac" placeholder="请选择生肖" filterable>
              <el-option v-for="item in zodiacDict" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="星座" prop="horoscope">
            <el-select v-model="state.form.horoscope" placeholder="请选择星座" filterable>
              <el-option v-for="item in horoscopeDict" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地区选择" prop="areaCode">
            <el-cascader
              v-model="areasParam.cityCodeList"
              :props="areasProps"
              @change="
                res =>
                  baseAreaConfirm({
                    res: res,
                    area: res[areasParam.level],
                    codeField: 'areaCode'
                  })
              "
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input
              type="textarea"
              maxlength="200"
              :rows="1"
              show-word-limit
              v-model="state.form.address"
              placeholder="请输入详细地址"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="评分" prop="star">
            <el-rate v-model="state.form.star" :texts="['1星', '2星', '3星', '4星', '5星']" show-text clearable></el-rate>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="复选框" prop="checkbox">
            <el-checkbox-group v-model="state.form.checkbox">
              <el-checkbox v-for="item in state.checkboxList" :value="item.value" name="type"> {{ item.label }} </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="取色器" prop="color">
            <el-color-picker v-model="state.form.color" show-alpha :predefine="predefineColors" @change="colorChange" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有输入框的滑块" prop="slider">
            <el-slider v-model="state.form.slider" show-input />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开关" prop="switch">
            <el-switch
              v-model="state.form.switch"
              active-text="开"
              inactive-text="关"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              active-value="1"
              inactive-value="0"
              @change="e => switchChange({ e: e })"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期段" prop="daterange">
            <el-date-picker
              v-model="state.form.daterange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDateRange"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期时间" prop="datetime">
            <el-date-picker
              v-model="state.form.datetime"
              type="datetime"
              placeholder="选择日期时间"
              @change="changeDateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期时间段" prop="datetimerange">
            <el-date-picker
              v-model="state.form.datetimerange"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期时间"
              end-placeholder="结束日期时间"
              @change="changeDateTimeRange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时间" prop="time">
            <el-time-select
              v-model="state.form.time"
              style="width: 100%"
              start="00:00"
              step="00:30"
              end="23:59"
              placeholder="选择时间"
              format="hh:mm A"
            />
          </el-form-item>
        </el-col>
        <!--  -->
        <el-col :span="12">
          <el-form-item label="时间段" prop="timerange">
            <div class="flx-center">
              <el-time-select
                v-model="state.form.startTime"
                :max-time="state.form.endTime"
                placeholder="开始时间"
                start="08:30"
                step="00:15"
                end="18:30"
                style="width: 200px"
                @change="validateTimeRange"
              />
              <el-time-select
                v-model="state.form.endTime"
                :min-time="state.form.startTime"
                placeholder="结束时间"
                start="08:30"
                step="00:15"
                end="18:30"
                class="ml10"
                style="width: 200px"
                @change="validateTimeRange"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审核" prop="type">
            <el-radio-group v-model="state.form.type" @change="typeChange">
              <el-radio value="1" size="large">审核通过</el-radio>
              <el-radio value="2" size="large">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="state.form.type == 2">
          <el-form-item label="失败原因" prop="reason">
            <el-input
              type="textarea"
              maxlength="200"
              :rows="3"
              show-word-limit
              v-model="state.form.reason"
              placeholder="请输入失败原因"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row type="flex" justify="center" style="margin: 20px 0">
      <el-button @click="submitForm" type="primary">提交</el-button>
      <el-button @click="resetForm(formRef)">重置</el-button>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeMount, getCurrentInstance, nextTick, watch, onBeforeUnmount } from "vue";
import { Check, Close } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { getIdCardInfo, dictReturn } from "@/utils/getSome";
import { genderDict, zodiacDict, horoscopeDict } from "@/utils/dict";
import { validatePassword } from "@/utils/eleValidate";
// import { findSubAreas } from "@/api/modules/areas"; // 接口地区数据
// import localAreaData from "@/assets/json/areaLevel3.min.json"; // 本地地区json数据
// import localAreaData from "@/assets/json/areaLevel4.min.json"; // 本地地区json数据
import { getReadFiles } from "@/api/modules/system"; // 获取文件
const state = reactive({
  checkboxList: [
    {
      label: "选择1",
      value: 1
    },
    {
      label: "选择2",
      value: 2
    },
    {
      label: "选择3",
      value: 3
    },
    {
      label: "选择4",
      value: 4
    }
  ],
  form: {
    name: "",
    password: "",
    idCard: "",
    gender: "",
    age: 1, // 数字输入框
    birthday: "", // 日期选择器
    zodiac: "", // 下拉框
    horoscope: "", // 下拉框
    areaCode: "", // 地区code
    address: "", // 文本框
    type: "1", // 单选框
    reason: "", // 文本域
    star: 0, // 评分
    checkbox: [], // 复选框
    color: "", // 颜色选择器
    slider: 0, // 滑块输入框
    switch: "0", // 开关

    daterange: [], // 日期范围
    startDate: "", // 开始日期
    endDate: "", // 结束日期

    datetime: "", // 日期时间选择器

    datetimerange: [], // 日期时间范围
    dateStartDate: "", // 开始日期时间
    dateEndDate: "", // 结束日期时间

    time: "", // 时间选择器

    startTime: "", // 开始时间
    endTime: "" // 结束时间
  }
});

// #region 表单校验
// 校验规则及参数
const formRef = ref();
const formRules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名至少2字到10字", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { validator: validatePassword, trigger: "blur" }
  ],
  idCard: [{ required: true, message: "请输入身份证号码", trigger: "blur" }],
  gender: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change"
    }
  ],
  type: [{ required: true, message: "请选择", trigger: "change" }],
  reason: null,
  star: [
    { required: true, message: "评分不能为空", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 5,
      message: "评分必须在1星到5星之间",
      trigger: "blur"
    }
  ],
  birthday: [
    {
      type: "date",
      required: true,
      message: "请选择出生日期",
      trigger: "change"
    }
  ],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 300,
      message: "年龄必须在1到300之间",
      trigger: "blur"
    }
  ],
  zodiac: [
    {
      required: true,
      message: "请选择生肖",
      trigger: "change"
    }
  ],
  horoscope: [
    {
      required: true,
      message: "请选择星座",
      trigger: "change"
    }
  ],
  areaCode: [
    {
      type: "string",
      required: true,
      message: "请选择地区",
      trigger: "change"
    }
  ],
  address: [
    {
      type: "string",
      required: true,
      message: "请输入详细地址",
      trigger: "blur"
    },
    { min: 1, max: 200, message: "地址在1到200个字符之间", trigger: "blur" }
  ],
  color: [
    {
      required: true,
      message: "请选择颜色",
      trigger: "change"
    }
  ],
  slider: [
    {
      type: "number",
      required: true,
      message: "请输入滑块数值",
      trigger: "blur"
    },
    {
      type: "number",
      min: 1,
      max: 100,
      message: "滑块数值必须在0到100之间",
      trigger: "blur"
    }
  ],
  checkbox: [
    {
      type: "array",
      required: true,
      message: "请选择多选框",
      trigger: "change"
    }
  ],
  switch: [
    {
      type: "string",
      required: true,
      message: "请选择开关状态",
      trigger: "change"
    }
  ],
  daterange: [
    {
      type: "array",
      required: true,
      message: "请选择日期范围",
      trigger: "change"
    }
  ],
  datetime: [
    {
      type: "date",
      required: true,
      message: "请选择日期时间",
      trigger: "change"
    }
  ],
  datetimerange: [
    {
      type: "array",
      required: true,
      message: "请选择日期时间范围",
      trigger: "change"
    }
  ],
  time: [
    {
      type: "string",
      required: true,
      message: "请选择时间",
      trigger: "change"
    }
  ],
  timerange: [
    {
      required: true,
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!state.form.startTime || !state.form.endTime) {
          callback(new Error("请选择完整的时间段"));
        } else if (state.form.endTime <= state.form.startTime) {
          callback(new Error("结束时间必须晚于开始时间"));
        } else {
          callback();
        }
      }
    }
  ]
});

// 校验方法
const validateForm = async () => {
  try {
    await formRef.value.validate(); // 校验多个表单
    // await FamilyRule.value.validate();
    // await SkillRule.value.validate();
    // await StudyRule.value.validate();
    // await InsureRule.value.validate();
    // await HonorRule.value.validate();
    // await HealthRule.value.validate();
    // await TrainRule.value.validate();
    return true; // 校验通过
  } catch (error) {
    console.log(error);
    return false; // 校验失败
  }
};

// 提交表单
const activityEnter = () => {
  console.log(state.form);
};

// 提交校验
const submitForm = async () => {
  const isValid = await validateForm();
  if (isValid) {
    // 表单校验通过，执行提交操作
    console.log("表单校验成功");
    activityEnter();
  } else {
    // 表单校验失败，显示错误信息
    console.log("表单校验失败");
  }
};

// 重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  areasParam.cityCodeList = [];
  state.form.startTime = "";
  state.form.endTime = "";
};
// #endregion

// #region 取色器
const predefineColors = ref([
  "#ff4500",
  "#ff8c00",
  "#ffd700",
  "#90ee90",
  "#00ced1",
  "#1e90ff",
  "#c71585",
  "rgba(255, 69, 0, 0.68)",
  "rgb(255, 120, 0)",
  "hsv(51, 100, 98)",
  "hsva(120, 40, 94, 0.5)",
  "hsl(181, 100%, 37%)",
  "hsla(209, 100%, 56%, 0.73)",
  "#c7158577"
]);
const colorChange = e => {
  console.log(e);
  ElMessage.success(`选中的颜色是：${e}`);
};
// #endregion

// #region 输入框
const idCardChange = e => {
  // console.log(e);
  const reg = /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/;
  if (reg.test(e)) {
    const info = getIdCardInfo(e, "value", true);
    console.log(info);
    state.form.age = info.age;
    state.form.gender = info.gender;
    state.form.birthday = info.birthday;
    state.form.zodiac = info.zodiac;
    state.form.horoscope = info.horoscope;
    state.form.areaCode = info.areaCode;
    areasParam.cityCodeList = [
      info.areaCode.substring(0, 2) + "0000000000",
      info.areaCode.substring(0, 4) + "00000000",
      info.areaCode
    ];
  } else {
    // ElMessage.error("身份证号格式不正确");
  }
};
// #endregion

// #region 单选框
const typeChange = e => {
  if (e == 2) {
    console.log(e);
    formRules.reason = [
      { required: true, message: "请输入失败原因", trigger: "blur" },
      { min: 1, max: 200, message: "失败原因在1到200个字符之间", trigger: "blur" }
    ];
  } else {
    formRules.reason = null;
    state.form.reason = "";
  }
};
// #endregion

// #region 地区选择模块

// 地区组件参数
const areasParam = reactive({
  localAreaData: [], // 本地地区数据
  useLocalAreasData: true, // true=使用本地地区json数据，false=使用接口地区数据
  level: 2, // 地区层级（层级=-1）（0-省（一级）, 1-市（二级）, 2-区/县（三级）, 3-镇/街道（四级））
  cityCodeList: [], // 地区数组
  labelName: "name", // 自定义label属性名
  valueName: "code", // 自定义name属性名
  keyName: "id" // 自定义唯一标识
});

// 地区选择最终获取数据
const baseAreaConfirm = e => {
  // console.log(e);
  state.form[e.codeField] = e.area;
};

// 获取地区列表（本地数据）
const getLocalAreas = async ({ parentCode, key }) => {
  const findAreaByCode = (areas, code) => {
    for (let area of areas) {
      // 根据是否有id来决定判断条件
      const isMatch =
        key !== undefined
          ? area[areasParam.valueName] === code && area[areasParam.keyName] == key
          : area[areasParam.valueName] === code;
      if (isMatch) {
        return area;
      }
      if (area.children && area.children.length > 0) {
        const result = findAreaByCode(area.children, code);
        if (result) {
          return result;
        }
      }
    }
    return null;
  };
  const root = findAreaByCode(areasParam.localAreaData, parentCode);
  return root ? root.children : areasParam.localAreaData;
};

// 获取地区列表文件数据
const getReadAreaFiles = async () => {
  const res = await getReadFiles({
    fileName: "areaLevel3.min.json"
  });
  if (res.code == 200) {
    areasParam.localAreaData = JSON.parse(res.data);
  } else {
    ElMessage.error("获取地区列表文件数据失败");
    console.error("获取地区列表文件数据失败", res);
    return;
  }
};

// 获取地区列表（接口数据）
const getApiAreas = ({ parentCode }) => {
  return new Promise((resolve, reject) => {
    findSubAreas({ parentCode }).then(res => {
      resolve(res.data);
    });
  });
};

// 地区Cascader级联选择器加载
const areasProps = {
  lazy: true,
  async lazyLoad(node, resolve) {
    const level = node.level;
    const parentCode = level === 0 ? 0 : node.value;
    const key = node.data.key;
    let data = [];
    if (areasParam.useLocalAreasData && areasParam.localAreaData.length === 0) {
      await getReadAreaFiles();
    }
    if (areasParam.useLocalAreasData) {
      // 从本地数据获取
      data = await getLocalAreas({ parentCode, key: key });
    } else {
      // 从接口获取
      data = await getApiAreas({ parentCode });
    }
    const options = data.map(item => ({
      value: item[areasParam.valueName],
      label: item[areasParam.labelName],
      leaf: level >= areasParam.level,
      key: item[areasParam.keyName] // 保留自定义唯一标识字段
    }));
    resolve(options);
  }
};
// #endregion

// #region 开关
const switchChange = ({ e }) => {
  const originalValue = state.form.switch == "1" ? "0" : "1"; // 记录原始状态
  const switchLabel = e == "1" ? "开启" : "关闭";
  ElMessageBox.confirm(`${switchLabel}开关？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      ElMessage.success(state.form.switch);
    })
    .catch(() => {
      state.form.switch = originalValue;
    });
};
// #endregion

// #region 日期段选择器
const changeDateRange = e => {
  // console.log(e);
  // state.form.startDate = `${e[0]} 00:00:00`;
  // state.form.endDate = `${e[1]} 23:59:59`;
  state.form.startDate = e ? e[0] : "";
  state.form.endDate = e ? e[0] : "";
  console.log(state.form);
};
// #endregion

// #region 日期时间选择器
const changeDateTime = e => {
  console.log(e);
  // state.form.datetime = `${e} 00:00:00`;
  // state.form.datetime = e;
  console.log(state.form);
};
// #endregion

// #region 日期时间段选择器
const changeDateTimeRange = e => {
  console.log(e);
  state.form.dateStartDate = e ? e[0] : "";
  state.form.dateEndDate = e ? e[0] : "";
  console.log(state.form);
};
// #endregion

// #region 时间段选择器
const validateTimeRange = () => {
  // 触发表单校验
  formRef.value.validateField("timerange");
};
// #endregion
</script>

<style lang="scss" scoped></style>
